<!--
 * @Description: 审核交车/详情
 * @Autor: 何兴家
 * @Date: 2021-05-17 09:37:41
 * @LastEditors: 马毅
 * @LastEditTime: 2021-07-13 15:00:08
-->
<template>
  <div>
    <div v-loading="pageLoading">
      <FormPanel ref="orderInfoForm" :list="formList" :isSubmitBtn="false"></FormPanel>

      <div v-for="(item, index) in renderList" :key="index">
        <BreakSpace v-if="item.field == 'breakSpace'" :label="item.label" :containerStyle="{ margin: '10px 0' }"></BreakSpace>
        <div v-else class="checkboxItem">
          <label :for="item.field" style="margin-left:30px">{{ item.label }}</label>
          <div class="inputItme">
            <input v-if="item.type != 1 && item.type != 2 && item.type != 0" v-model="checkboxValue[item.field]" type="checkbox" :id="item.field" :disabled="pageType == 'detail'" />
            <!-- <el-radio-group v-model="checkboxValue[item.field].status" v-if="item.type == 0"> -->
            <!-- <el-radio-button v-if="item.type == 0" label="1" :id="item.field1" :disabled="pageType == 'detail'" :change="changeStatue(item.field)">是</el-radio-button> -->
            <!-- <el-radio-button v-if="item.type == 0" label="0" :id="item.field0" :disabled="pageType == 'detail'" :change="changeStatue(item.field)">否</el-radio-button> -->
            <!-- </el-radio-group> -->
            <div class="flexWrap">
              <el-radio v-if="item.type == 0" v-model="checkboxValue[item.field].status" label="1" :id="item.field1" :disabled="pageType == 'detail'" :change="changeStatue(item.field)">是</el-radio>
              <el-radio v-if="item.type == 0" v-model="checkboxValue[item.field].status" label="0" :id="item.field0" :disabled="pageType == 'detail'" :change="changeStatue(item.field)">否</el-radio>
            </div>
            <div class="flexWrap">
              <div v-if="item.type == 2">左前</div>
              <input v-if="item.type == 2" style="width: 40px" type="input" v-model="checkboxValue[item.field].leftFront" :id="item.field + 'leftFront'" :disabled="pageType == 'detail'" />
            </div>
            <div class="flexWrap">
              <div v-if="item.type == 2">右前</div>
              <input v-if="item.type == 2" style="width: 40px" type="input" v-model="checkboxValue[item.field].rightFront" :id="item.field + 'rightFront'" :disabled="pageType == 'detail'" />
            </div>

            <div class="flexWrap">
              <div v-if="item.type == 2">左后</div>
              <input v-if="item.type == 2" style="width: 40px" type="input" v-model="checkboxValue[item.field].leftBehind" :id="item.field + 'leftBehind'" :disabled="pageType == 'detail'" />
            </div>

            <div class="flexWrap">
              <div v-if="item.type == 2">右后</div>
              <input v-if="item.type == 2" style="width: 40px" type="input" v-model="checkboxValue[item.field].rightBehind" :id="item.field + 'rightBehind'" :disabled="pageType == 'detail'" />
            </div>

            <div class="flexWrap">
              <div v-if="item.type == 0 || item.type == 2" style="margin-left:30px">其他</div>
              <div v-if="item.type == 1">结果</div>
              <input
                :ref="item.field + 'other'"
                v-if="item.type || item.type == 0"
                style="width: 300px"
                type="input"
                v-model="checkboxValue[item.field].other"
                :id="item.field + 'other'"
                :disabled="pageType == 'detail'"
              />
              <!-- || (checkboxValue[item.field].status != 1 && item.type != 1) -->
            </div>
          </div>
        </div>
      </div>
      <div class="inputItme1">
        <div style="margin-left:30px">备注</div>
        <input style="width: 500px;margin-left:50px" type="input" v-model="checkboxValue.remark" :id="'remark'" :disabled="pageType == 'detail'" />
      </div>

      <BreakSpace
        label="整车照片1张(必传),仪表1张(必传),维修部位照片1张(必传),旧件照片(非必传,换件时),电池照片(必传),如果有损伤上传损伤部位照片(全景,近景,深度,长度)"
        :containerStyle="{ margin: '10px 0' }"
      ></BreakSpace>
      <FormPanel ref="uploadImgForm" :list="uploadFormList" :isSubmitBtn="false" :cols="4"></FormPanel>
    </div>
    <div class="dialogBottmView">
      <el-button @click="handleClose">取消</el-button>
      <AjaxButton v-show="pageType == 'audit'" :disabled="pageLoading" type="primary" :click="handleComfirm">确定</AjaxButton>
    </div>
  </div>
</template>

<script>
import _ from 'lodash';
import { dictionary } from '@/utils/dictMixin';
import moment from 'moment';
import { confirmAction, notifyAction, findFormItem, findTableItem } from '@/utils';
import dictCode from '@/utils/dictCode';

import { examTestOrder, getTestOrderDetails } from '@/api/repair/repairReception/submitForSettlement';
import { searchRoleByCodes } from '@/api/common/empSelect/index';

export default {
  mixins: [dictionary],
  props: ['rowData', 'pageType'],
  data() {
    this.renderList = [
      { label: '维修项目情况(需要全部勾选)', field: 'breakSpace' },
      { label: '安装合格', field: 'isInstallQualified' },
      { label: '功能测试合格', field: 'isFunctionQualified' },
      { label: '施工部位清洁', field: 'isBuildQualified' },
      // { label: '是否内饰无额外损坏', field: 'isAdditionalDamage' },
      { label: '告警灯点亮', field: 'isWarningLight' },
      { label: '车辆大版本为最新', field: 'isNew' },

      { label: '项目检查情况', field: 'breakSpace' },
      { label: '车辆外观常规检查是否异常', field: 'isOutsideGood', type: 0 },
      { label: '车灯常规检查是否异常', field: 'isLightGood', type: 0 },
      // { label: '轮胎常规检查无异常', field: 'isTyreGood' },
      { label: '制动液检查是否异常', field: 'ifBreakBlockGood', type: 0 },
      { label: '冷却液常规检查是否异常', field: 'isAntifreezeGood', type: 0 },
      { label: '冷却液冰点检查', field: 'icePointCheckAnti', type: 1 },
      { label: '玻璃水常规检查是否异常', field: 'isGlassGood', type: 0 },
      { label: '玻璃水冰点检查', field: 'icePointCheckGlass', type: 1 },
      { label: '轮胎气压', field: 'tirePressure', type: 0 },
      { label: '轮胎花纹深度', field: 'treadDepth', type: 0 },
      { label: '制动片厚度', field: 'brakePadThickness', type: 0 },
      { label: '制动盘厚度', field: 'brakeDiscThickness', type: 0 },
      // { label: '车辆【油/液】剩余容量正常', field: 'isCapacityGood' },
      // { label: '交车电量不低于接车电量', field: 'isPowerGood' },
      { label: '低电压蓄电池健康度', field: 'isDamageBattery', type: 1 }
      // { label: '车辆清洗检查（如有洗车）', field: 'breakSpace' },
      // { label: '车身内外饰件无水珠,无水渍,无泡沫残留', field: 'isInsideWaterGood' },
      // { label: '玻璃内外饰件无水珠、无水渍、无泡沫残留', field: 'isOutsideWaterGood' },
      // { label: '前机舱无明显灰尘', field: 'isDustFront' },
      // { label: '轮胎清洁无污垢', field: 'isDustTyre' },
      // { label: '轮毂清洁无污垢', field: 'isDustHub' },
      // { label: '异物有无无法取出的沥青等异物', field: 'isDustRarity' },

      // { label: '动力电池情况', field: 'breakSpace' },
    ];

    return {
      formList: this.createFormList(),
      uploadFormList: this.createUploadFormList(),
      pageLoading: false,
      checkboxValue: {
        isInstallQualified: false,
        isFunctionQualified: false,
        isBuildQualified: false,
        isAdditionalDamage: false,
        isWarningLight: false,
        isNew: false,
        isOutsideGood: { status: undefined, type: 0 },
        isLightGood: { status: undefined, type: 0 },
        isTyreGood: false,
        ifBreakBlockGood: { status: undefined, type: 0 },
        isGlassGood: { status: undefined, type: 0 },
        isAntifreezeGood: { status: undefined, type: 0 },
        isCapacityGood: false,
        isPowerGood: false,
        isInsideWaterGood: false,
        isOutsideWaterGood: false,
        isDustFront: false,
        isDustTyre: false,
        isDustHub: false,
        isDustRarity: false,
        isDamageBattery: { type: 1, other: null },
        icePointCheckAnti: { type: 1, other: null },
        icePointCheckGlass: { type: 1, other: null },
        tirePressure: { type: 0, other: null, status: undefined, rightFront: null, leftBehind: null, rightBehind: null },
        treadDepth: { type: 0, other: null, status: undefined, rightFront: null, leftBehind: null, rightBehind: null },
        brakePadThickness: { type: 0, other: null, status: undefined, rightFront: null, leftBehind: null, rightBehind: null },
        brakeDiscThickness: { type: 0, other: null, status: undefined, rightFront: null, leftBehind: null, rightBehind: null },
        remark: null
      }
    };
  },
  mounted() {
    this.rowData && this.initOrderData();
    this.pageType == 'detail' && this.disabledPageFrom();
    this.queryServiceAdviserList();
  },
  methods: {
    createFormList() {
      return [
        {
          type: 'BREAK_SPACE',
          label: '工单信息'
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '车牌',
          fieldName: 'license',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '客户名称',
          fieldName: 'ownerName',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '工单号',
          fieldName: 'roNo',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '车型',
          fieldName: 'modelName',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '有效时间',
          fieldName: 'effectiveTime',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '续航里程',
          fieldName: 'remainingMileage',
          disabled: true
        },
        {
          type: 'SELECT',
          label: '质检员',
          fieldName: 'inspector',
          itemList: [],
          rules: [{ required: true, message: '请选择质检员', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '预交车时间',
          fieldName: 'endTimeSupposed',
          disabled: true
        }
      ];
    },
    createUploadFormList() {
      return [
        {
          type: 'UPLOAD_IMG',
          fieldName: 'picPath1',
          disabled: false,
          initialValue: [],
          upload: {
            actionUrl: '/api/file/oss/upload',
            limit: 15
          }
        }
      ];
    },
    changeStatue(val) {
      if (this.pageType != 'detail') {
        this.checkboxValue[val].other = undefined;
      }
    },
    // 初始化工单数据
    async initOrderData() {
      this.pageLoading = true;
      try {
        let res = await getTestOrderDetails(this.rowData.roNo);
        if (res.resultCode == 200) {
          // 工单信息
          this.formList.forEach(item => {
            if (item.fieldName == 'effectiveTime' && this.pageType != 'detail') {
              let endTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
              let startTime = moment(res.data.roCreateDate).format('YYYY-MM-DD HH:mm:ss');
              item.initialValue = (moment(endTime).diff(moment(startTime), 'seconds') / 60 / 60).toFixed(2);
            } else {
              item.initialValue = res.data[item.fieldName];
            }
          });

          // 处理勾选数据
          Object.keys(this.checkboxValue).forEach(item => {
            if (this.checkboxValue[item] != null) {
              if (this.checkboxValue[item].type == 0) {
                if (res.data.repairCheckDTO[item].status) {
                  let status = res.data.repairCheckDTO[item].status == 10041001 ? '1' : '0';
                  this.checkboxValue[item].status = status;
                }
              } else if (!this.checkboxValue[item].type) {
                this.checkboxValue[item] = res.data.repairCheckDTO[item] == 10041001 ? true : false;
              }
            }
          });
          //处理文字
          Object.keys(this.checkboxValue).forEach(item => {
            if (item == 'remark') {
              this.checkboxValue[item] = res.data.repairCheckDTO[item];
            }
            if (this.checkboxValue[item] != null) {
              if (this.checkboxValue[item].type == 0) {
                this.checkboxValue[item].other = res.data.repairCheckDTO[item].other;
              } else if (this.checkboxValue[item].type == 1) {
                this.checkboxValue[item].other = res.data.repairCheckDTO[item];
              } else if (this.checkboxValue[item].type == 2) {
                this.checkboxValue[item].leftFront = res.data.repairCheckDTO[item].leftFront;
                this.checkboxValue[item].rightFront = res.data.repairCheckDTO[item].rightFront;
                this.checkboxValue[item].leftBehind = res.data.repairCheckDTO[item].leftBehind;
                this.checkboxValue[item].rightBehind = res.data.repairCheckDTO[item].rightBehind;
                this.checkboxValue[item].other = res.data.repairCheckDTO[item].other;
              }
            }
          });
          // 上传图片
          if (res.data.photoList && res.data.photoList.length > 0) {
            this.uploadFormList[0].initialValue = res.data.photoList;
            // let i = 0;
            // this.uploadFormList.forEach(item => {
            //   if(res.data.photoList[i]){
            //   item.initialValue = [res.data.photoList[i]];
            //   }
            //   i++;
            // });
          }
        }
      } catch (err) {
        console.log(err, '初始化工单数据失败');
      } finally {
        this.pageLoading = false;
      }
    },
    // 获取服务顾问列表
    async queryServiceAdviserList() {
      let inspector = { role: '10061011,10071011,10071031,10071037,10071038,10071039' };
      let serviceConsultant = { role: dictCode.SERVICE_CONSULTANT };
      let res = await searchRoleByCodes(inspector);
      if (res.resultCode == 200) {
        let serviceAdviserDict = res.data.map(item => ({ text: item.employeeName, value: item.userId + '' }));
        findFormItem(this.formList, 'inspector').itemList = serviceAdviserDict;
      }
    },
    // 关闭弹窗
    handleClose() {
      this.$emit('close');
    },
    // 禁用页面表单
    disabledPageFrom() {
      this.formList.forEach(item => (item.disabled = true));
      this.uploadFormList.forEach(item => (item.disabled = true));
    },
    // 点击提交
    async handleComfirm() {
      console.log(JSON.parse(JSON.stringify(this.checkboxValue)));
      let orderFormData = await this.$refs.orderInfoForm.GET_FORM_DATA();
      let photoFormData = await this.$refs.uploadImgForm.GET_FORM_DATA();

      if (orderFormData[0] || photoFormData[0]) return;
      let submitCheckData = {};
      // 拼接勾选数据
      Object.keys(this.checkboxValue).forEach(item => {
        let obj = this.checkboxValue[item];
        console.log(item, obj);
        // console.log('itemType::', obj.type);
        if (obj != null && (obj.type || obj.type == 0)) {
          switch (obj.type) {
            case 0:
              let status = undefined;
              if (this.checkboxValue[item].status) {
                status = this.checkboxValue[item].status == '1' ? 10041001 : 10041002;
              }
              submitCheckData[item] = { status: status, other: this.checkboxValue[item].other };
              break;
            case 1:
              submitCheckData[item] = this.checkboxValue[item].other;
              break;
            case 2:
              submitCheckData[item] = {
                leftFront: this.checkboxValue[item].leftFront,
                rightFront: this.checkboxValue[item].rightFront,
                leftBehind: this.checkboxValue[item].leftBehind,
                rightBehind: this.checkboxValue[item].rightBehind,
                other: this.checkboxValue[item].other
              };
              break;
          }
        } else {
          submitCheckData[item] = this.checkboxValue[item] ? 10041001 : 10041002;
          if (item == 'remark') {
            submitCheckData[item] = this.checkboxValue[item];
          }
        }
      });
      console.log('勾选处理完毕');
      // 处理照片数据
      let phothData = photoFormData[1]['picPath1'];
      // Object.keys(photoFormData[1]).forEach((item, index) => {
      //   phothData[index] = photoFormData[1][item] || null;
      // });
      if (phothData.length < 4) {
        notifyAction('图片不得小于4张', 'warning');
        return;
      }
      let res = await examTestOrder({ ...orderFormData[1], photoList: phothData, ...submitCheckData, deliveryTag: 10041001 });
      if (res.resultCode == 200) {
        notifyAction('审核成功', 'success');
        this.$emit('refesh');
        this.handleClose();
      }
    }
  }
};
</script>

<style scoped>
.flexWrap {
  display: flex;
}
.checkboxItem {
  display: flex;
  justify-content: space-between;
  align-items: center;
  user-select: none;
}
.checkboxItem input {
  width: 16px;
  height: 16px;
}
.checkboxItem label {
  cursor: pointer;
}
.inputItme {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  width: 50%;
}
.inputItme1 {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  width: 50%;
}
.inputItme input {
  border: none;
  border-bottom: 1px solid black;
}
</style>
